package com.blog.security.service;

import cn.hutool.core.lang.UUID;
import com.common.redis.service.RedisService;
import com.comon.core.constants.CacheConstants;
import com.comon.core.constants.JwtConstants;
import com.comon.core.domain.entity.LoginUser;
import com.comon.core.utils.JwtUtils;
import com.comon.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-08-24
 * Time:21:37
 * Text：
 */
@Service
public class TokenService {
    @Autowired
    private RedisService redisService;

    public String createToken(Long userId,String phone,String secret,String nickName,Integer identity){
        //生成Token
        Map<String,Object> claims = new HashMap<>();
        String userUUID = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID,userId);
        claims.put(JwtConstants.LOGIN_USER_USERNAME,nickName);
        claims.put(JwtConstants.LOGIN_USER_UUID,userUUID);
        claims.put(JwtConstants.LOGIN_USER_identity,identity);
        claims.put(JwtConstants.LOGIN_USER_PHONE,phone);
        String token = JwtUtils.createToken(claims,secret);
        //存储到redis当中

        String key = getTokenKey(userUUID);

        LoginUser loginUser = new LoginUser();
        loginUser.setPhone(phone);
        loginUser.setIdentity(identity);
        redisService.setCacheObject(key,loginUser,CacheConstants.EXP,TimeUnit.MINUTES);

        return token;
    }

    private String getTokenKey(String userUUID) {
        return CacheConstants.LOGIN_TOKEN_KEY + userUUID;
    }

    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userkey = JwtUtils.getUserUUID(token);
            redisService.deleteObject(getTokenKey(userkey));
        }
    }
}
